//
//  NetHandleData.m
//  Everest
//
//  Created by 李其昌 on 15/1/4.
//  Copyright (c) 2015年 ThreeL. All rights reserved.
//

#import "NetHandleData.h"

@implementation NetHandleData
+ (void)getDataWithUrl:(NSString *)str completion:(void (^)(NSData *data))block
{
    NSString *urlStr = [str stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSURL *url = [NSURL URLWithString:urlStr];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60];
    request.HTTPMethod = @"GET";
    // 建立连接(异步处理)
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        // 处理数据
        // 1.确定地址
        NSString *docPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
        NSString *path = [NSString stringWithFormat:@"%@/%ld.aa", docPath, [str hash]];
        
        if (data != nil) {
            BOOL result = [NSKeyedArchiver archiveRootObject:data toFile:path];
            //            NSLog(@"%d", result);
            if (result == NO) {
                NSLog(@"数据请求失败");
            }
            // 当返回的数据不为空时, 调用block
            block(data);
        } else {
            // 没有网络或请求失败, 就从本地读取最近一次成功的数据
            NSData *pickData = [NSKeyedUnarchiver unarchiveObjectWithFile:path];
            if (pickData != nil) {
                // 确保有数据才返回
                block(pickData);
            }
        }
        // 让有关视图 刷新数据
        // tableView reloadData
        // label.text = ...
    }];

    
}
@end
